package com.sinodata.bsm.cicp.collector.vsphere;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.sinodata.bsm.cicp.collector.Collector;
import com.sinodata.bsm.cicp.exception.CollectorException;
import com.sinodata.bsm.cicp.util.CommandReader;
import com.sinodata.bsm.common.vo.ResPropertyValue;

public class NetworkCollector extends Collector {
    private static String CMD_STR = VsphereCollector.CMD_STR;

    @Override
    public List<ResPropertyValue> collect(String ip) throws CollectorException {
        String ifName = this.paramMap.get("IfName");
        List<String> keys = new ArrayList<String>();
        keys.add(ifName + ")\\Packets Transmitted/sec");
        keys.add(ifName + ")\\Packets Received/sec");

        BufferedReader reader = null;
        String strLine = null;
        boolean flag = true;
        String name = null;
        String value = null;
        List<ResPropertyValue> results = new ArrayList<ResPropertyValue>();
        try {
            reader = CommandReader.getReader(ip, CMD_STR, 60 * 1000, 0);
            while ((strLine = reader.readLine()) != null) {
                if (flag) {
                    name = strLine;
                    flag = false;
                } else {
                    value = strLine;
                }
            }
        } catch (IOException e) {
            logger.error("error execute esx host cmd : esxtop ", e);
        }

        if (name != null && value != null) {
            String[] names = name.split("[,]");
            String[] values = value.split("[,]");
            for (int i = 0; i < names.length; i++) {
                for (int j = 0; j < keys.size(); j++) {
                    if (names[i].indexOf(keys.get(j)) != -1) {
                        values[i] = org.apache.commons.lang.StringUtils.remove(values[i], "\"");
                        map.put(keys.get(j), values[i]);
                    }
                }
            }
        }
        String[] propMetas = getPropMeta();
        ResPropertyValue propertyValueX = new ResPropertyValue();
        ResPropertyValue.PropValue[] propValues = new ResPropertyValue.PropValue[propMetas.length];
        for (int i = 0; i < keys.size(); i++) {
            String val = map.get(keys.get(i));
            propValues[i] = ResPropertyValue.createPropValue(val, propMetas[i]);
        }
        propertyValueX.setValues(propValues);
        results.add(propertyValueX);
        return results;
    }

    @Override
    public String[] getParamMeta() {

        return new String[] { "ifName" };
    }

    private Map<String, String> map = new HashMap<String, String>();

    @Override
    public String[] getPropMeta() {
        return new String[] { "$1", "$2" };

    }

}
